package com.itruth.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import com.itruth.dao.UserDao;
import com.itruth.dao.impl.UserDaoImpl;
import com.itruth.entity.User;
import com.itruth.util.JsonUtil;
import com.opensymphony.xwork2.ActionSupport;

public class RegAction extends ActionSupport {
	
	private UserDao userDao;
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -9041261643125250119L;
	
	public RegAction() {
		userDao = new UserDaoImpl();
	}
	
	public void reg() {
		
		HttpServletRequest req = ServletActionContext.getRequest();
		HttpServletResponse res = ServletActionContext.getResponse();
		PrintWriter pw = null;
		
		try {
			
			JSONObject json = JsonUtil.parseInputStream(req.getInputStream());
			
			pw = res.getWriter();
			
			String userName = json.getString("username");
			String password = json.getString("password");
			
			System.out.println(userName + ", " + password);
			
			if (userDao.accountIsExist(userName)) {
				//账户已存在
				pw.write("0x01");
			} else {
				userDao.insert(new User(userName, password));
				pw.write("0x00");
			}
			pw.flush();
		} catch (IOException e) {
			
			//TODO 服务器错误
			
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (null != pw) {
				pw.close();
				pw = null;
			}
			
		}
		
		
	}
	
}
